package com.chhuang.huaao.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.chhuang.core.bean.QueryBean;
import com.chhuang.core.validation.ValidGroupUpdate;
import com.chhuang.huaao.bean.HaMachineQueryBean;
import com.chhuang.huaao.consts.HaConstact;
import com.chhuang.huaao.po.HaCustomer;
import com.chhuang.huaao.po.HaFeedback;
import com.chhuang.huaao.po.HaMachine;
import com.chhuang.huaao.service.IHaCustomerService;
import com.chhuang.huaao.service.IHaFeedbackService;
import com.chhuang.huaao.service.IHaMachineService;
import com.chhuang.huaao.thread.MachineBinStallThread;
import com.chhuang.huaao.thread.MachineFlushTask;
import com.chhuang.huaao.thread.MachineRecoverThread;
import com.chhuang.huaao.thread.MachineStatusFlushThread;
import com.chhuang.huaao.thread.MachineTempTimeoutThread;
import com.chhuang.huaao.thread.MachineTimeIntervalThread;
import com.chhuang.huaao.thread.MachineTurnOnThread;
import com.chhuang.huaao.thread.TokenFileThread;
import com.chhuang.huaao.util.BaiduGeocoderUtil;
import com.chhuang.huaao.vo.CustomerVo;
import com.chhuang.system.consts.SysConstants;
import com.chhuang.utils.Assert;
import com.chhuang.utils.config.SysConfig;
import com.chhuang.utils.file.FileUtil;
import com.chhuang.utils.string.Md5Util;

@Controller
@RequestMapping("/client/api")
public class ClientController {
	private static final Log log = LogFactory.getLog(ClientController.class);
	
	@Autowired
	private IHaCustomerService haCustomerService;
	@Autowired
	private IHaMachineService haMachineService;
	@Autowired
	private IHaFeedbackService haFeedbackService;

	/**
	 * 登录校验令牌
	 */
	public static Map<String, JSONObject> tokens = new Hashtable<String, JSONObject>();
	
	static{
		File file = new File(SysConfig.getValue(SysConstants.Config.CLIENT_TOKEN_PATH));
		if(file.exists()){
			try {
				FileInputStream freader = new FileInputStream(file);
				ObjectInputStream input = new ObjectInputStream(freader);
				tokens = (Map<String, JSONObject>) input.readObject();
				input.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 用户手机app登录
	 * @param customerAccount
	 * @param customerPassword
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/login.app",method=RequestMethod.POST)
	@ResponseBody
	public Object login(@RequestBody HaCustomer customer) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customer.getCustomerAccount()) && Assert.isValidString(customer.getCustomerPassword())){
			HaCustomer customerTemp = haCustomerService.findByCustomerAccount(customer.getCustomerAccount());
			String password = Md5Util.md5(customer.getCustomerPassword(), customer.getCustomerAccount());
			if(customerTemp!=null && password.equals(customerTemp.getCustomerPassword())){
				if(customerTemp.getLocked()==null || !customerTemp.getLocked()){
					if(Assert.isValidString(customer.getClientId()))
						customerTemp.setClientId(customer.getClientId());
					if(Assert.isValidString(customer.getClientVersion()))
						customerTemp.setClientVersion(customer.getClientVersion());
					if(Assert.isValidString(customer.getDeviceModel()))
						customerTemp.setDeviceModel(customer.getDeviceModel());
					if(Assert.isValidString(customer.getDeviceSystem()))
						customerTemp.setDeviceSystem(customer.getDeviceSystem());
					if(Assert.isValidString(customer.getDeviceUuid()))
						customerTemp.setDeviceUuid(customer.getDeviceUuid());
					if(Assert.isValidString(customer.getDeviceVendor()))
						customerTemp.setDeviceVendor(customer.getDeviceVendor());
					if(Assert.isValidString(customer.getLastLoginAddress()))
						customerTemp.setLastLoginAddress(customer.getLastLoginAddress());
					Date now = new Date();
					customerTemp.setLastLoginTime(now);
					customerTemp.setModifyTime(now);
					haCustomerService.update(customerTemp);

					HaCustomer temp = (HaCustomer) BeanUtils.cloneBean(customerTemp);
					json.put(SysConstants.Status.SUCCESS, true);
					temp.setCustomerPassword(null);
					json.put(SysConstants.Status.RESULT, temp);
					
					String token = UUID.randomUUID().toString().replaceAll("-", "");
					json.put(SysConstants.Token.TOKEN, token);
					JSONObject tokenObj = new JSONObject();
					tokenObj.put(SysConstants.Token.TOKEN, token);
					tokenObj.put(SysConstants.Token.TIME, System.currentTimeMillis());
					tokens.put(customerTemp.getCustomerId(), tokenObj);
					
					//把token写入文件
					new Thread(new TokenFileThread(tokens, SysConfig.getValue(SysConstants.Config.CLIENT_TOKEN_PATH))).start();
					
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "账号或密码不正确");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户账号或密码不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 用户手机app注册
	 * @param customerAccount
	 * @param customerPassword
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/regedit.app",method=RequestMethod.POST)
	@ResponseBody
	public Object regedit(@RequestBody HaCustomer customer) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customer.getCustomerAccount()) && Assert.isValidString(customer.getCustomerPassword())){
			Pattern pattern = Pattern.compile("/^1(3|4|5|7|8)\\d{9}$/");
			Matcher matcher = pattern.matcher(customer.getCustomerAccount());
			if(matcher.matches()){
				if(haCustomerService.findByCustomerAccount(customer.getCustomerAccount())==null){
					customer.setCustomerPhone(customer.getCustomerAccount());
					customer.setCustomerPassword(Md5Util.md5(customer.getCustomerPassword(), customer.getCustomerAccount()));
					
					Date now = new Date();
					customer.setLastLoginTime(now);
					customer.setModifyTime(now);
					customer.setCreateTime(now);
					haCustomerService.save(customer);
					
					HaCustomer temp = (HaCustomer) BeanUtils.cloneBean(customer);
					json.put(SysConstants.Status.SUCCESS, true);
					temp.setCustomerPassword(null);
					json.put(SysConstants.Status.RESULT, temp);
					
					String token = UUID.randomUUID().toString().replaceAll("-", "");
					json.put(SysConstants.Token.TOKEN, token);
					JSONObject tokenObj = new JSONObject();
					tokenObj.put(SysConstants.Token.TOKEN, token);
					tokenObj.put(SysConstants.Token.TIME, System.currentTimeMillis());
					tokens.put(customer.getCustomerId(), tokenObj);
					
					//把token写入文件
					new Thread(new TokenFileThread(tokens, SysConfig.getValue(SysConstants.Config.CLIENT_TOKEN_PATH))).start();
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "手机号已存在");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "手机号码格式不正确");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户账号或密码不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 获取用户信息
	 * @param customer
	 * @param bindingResult
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/findCustomer.app",method=RequestMethod.POST)
	@ResponseBody
	public Object findCustomer(@RequestBody HaCustomer customer) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customer.getCustomerId())){
			HaCustomer customerTemp = haCustomerService.findByPrimaryKey(customer.getCustomerId());
			if(customerTemp!=null){
				if(customerTemp.getLocked()==null || !customerTemp.getLocked()){
					if(Assert.isValidString(customer.getClientId()))
						customerTemp.setClientId(customer.getClientId());
					if(Assert.isValidString(customer.getClientVersion()))
						customerTemp.setClientVersion(customer.getClientVersion());
					if(Assert.isValidString(customer.getDeviceModel()))
						customerTemp.setDeviceModel(customer.getDeviceModel());
					if(Assert.isValidString(customer.getDeviceSystem()))
						customerTemp.setDeviceSystem(customer.getDeviceSystem());
					if(Assert.isValidString(customer.getDeviceUuid()))
						customerTemp.setDeviceUuid(customer.getDeviceUuid());
					if(Assert.isValidString(customer.getDeviceVendor()))
						customerTemp.setDeviceVendor(customer.getDeviceVendor());
					if(Assert.isValidString(customer.getLastLoginAddress()))
						customerTemp.setLastLoginAddress(customer.getLastLoginAddress());
					Date now = new Date();
					customerTemp.setLastLoginTime(now);
					customerTemp.setModifyTime(now);
					haCustomerService.update(customerTemp);
					
					json.put(SysConstants.Status.SUCCESS, true);
					customerTemp.setCustomerPassword(null);
					json.put(SysConstants.Status.RESULT, customerTemp);
					JSONObject tokenObj = tokens.get(customerTemp.getCustomerId());
					if(tokenObj!=null){
						String token = tokenObj.getString(SysConstants.Token.TOKEN);
						if(Assert.isValidString(token))
							json.put(SysConstants.Token.TOKEN, token);
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 用户修改密码
	 * @param customerId
	 * @param oldPassword
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/updatePassword.app",method=RequestMethod.POST)
	@ResponseBody
	public Object updatePassword(String customerId, String oldPassword, String password) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customerId) && Assert.isValidString(oldPassword) && Assert.isValidString(password)){
			HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
			if(customer!=null){
				if(customer.getLocked()==null || !customer.getLocked()){
					oldPassword = Md5Util.md5(oldPassword, customer.getCustomerAccount());
					if(oldPassword.equals(customer.getCustomerPassword())){
						customer.setCustomerPassword(Md5Util.md5(password, customer.getCustomerAccount()));
						customer.setModifyTime(new Date());
						if(haCustomerService.update(customer)>0){
							json.put(SysConstants.Status.SUCCESS, true);
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "修改密码失败");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "原密码不正确");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID或密码不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 修改个人信息
	 * @param customer
	 * @param bindingResult
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/editCustomer.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editCustomer(CustomerVo customer, HttpServletRequest request) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customer.getCustomerId())){
			HaCustomer customerTemp = haCustomerService.findByPrimaryKey(customer.getCustomerId());
			if(customerTemp!=null){
				if(customerTemp.getLocked()==null || !customerTemp.getLocked()){
					String filePath = null, oldPhoto = null;
					
					Date now = new Date();
					customerTemp.setModifyTime(now);
					customerTemp.setCustomerGender(customer.getCustomerGender());
					customerTemp.setCustomerName(customer.getCustomerName());
					customerTemp.setCustomerCompany(customer.getCustomerCompany());
					MultipartFile mfile = customer.getFile();
					if(mfile!=null && !mfile.isEmpty()){
						//文件保存路径 
						filePath = request.getSession().getServletContext().getRealPath("/");
						//文件原名
						String originalFilename = mfile.getOriginalFilename();
						//文件名
		                String filename = "Resource/"+UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
		                File file = new File(filePath+filename);
		                FileUtil.makeFilePath(file);
		                //转存文件 
		                mfile.transferTo(file);
		                oldPhoto = customerTemp.getCustomerPhoto();
		                customerTemp.setCustomerPhoto(filename);
					}
					if(haCustomerService.update(customerTemp)>0){
						json.put(HaConstact.CUSTOMER_ID, customerTemp.getCustomerId());
						json.put(SysConstants.Status.SUCCESS, true);
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "修改个人信息失败");
					}
					if(Assert.isValidString(oldPhoto)){
						FileUtils.deleteQuietly(new File(filePath+oldPhoto));
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户账号不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 用户修改设备信息
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editMachineBaseInfo.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineBaseInfo(@RequestBody @Validated(value={ValidGroupUpdate.class}) HaMachine machine, BindingResult bindingResult) throws Exception{
		JSONObject json = new JSONObject();
		if(bindingResult.hasErrors()){
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			log.debug(json.toString());
			return json;
		}
		if(Assert.isValidString(machine.getMachineId())){
			HaMachine machineTemp = haMachineService.findByPrimaryKey(machine.getMachineId());
			if(machineTemp!=null){
				if(Assert.isValidString(machine.getCustomerId()) && machine.getCustomerId().equals(machineTemp.getCustomerId())){
					HaCustomer customer = haCustomerService.findByPrimaryKey(machine.getCustomerId());
					if(customer!=null){
						if(customer.getLocked()==null || !customer.getLocked()){
							Date now = new Date();
							machineTemp.setModifyTime(now);
							machineTemp.setMachineCname(machine.getMachineCname());//用户使用的设备别名
							//另外三个只能查看的管理员
							machineTemp.setCustomerId1(newOrfindCustomer(machine.getCustomerId1()));
							machineTemp.setCustomerId2(newOrfindCustomer(machine.getCustomerId2()));
							machineTemp.setCustomerId3(newOrfindCustomer(machine.getCustomerId3()));
							
							if(haMachineService.update(machineTemp)>0){
								json.put(HaConstact.MACHINE_ID, machineTemp.getMachineId());
								json.put(SysConstants.Status.SUCCESS, true);
							}else{
								json.put(SysConstants.Status.SUCCESS, false);
								json.put(SysConstants.Status.RESULT, "修改设备信息失败");
							}
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "用户账号不存在");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户没有权限修改此设备的参数");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 新建用户
	 * @param phone
	 * @return
	 * @throws Exception 
	 */
	private String newOrfindCustomer(String phone) throws Exception{
		if(Assert.isInvalidString(phone)){
			return null;
		}
		HaCustomer customerTemp = haCustomerService.findByCustomerAccount(phone);
		if(customerTemp==null){
			customerTemp = new HaCustomer();
			customerTemp.setCustomerAccount(phone);
			customerTemp.setCustomerPhone(phone);
			customerTemp.setCustomerPassword(Md5Util.md5(phone, phone));
			customerTemp.setLocked(false);
			Date now = new Date();
			customerTemp.setCreateTime(now);
			customerTemp.setModifyTime(now);
			haCustomerService.save(customerTemp);
		}
		return customerTemp.getCustomerId();
	}
	
	/**
	 * 校验用户输入的密码
	 * @param customerId
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/checkPassword.app",method=RequestMethod.POST)
	@ResponseBody
	public Object checkPassword(String customerId, String password) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customerId) && Assert.isValidString(password)){
			HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
			if(customer!=null){
				log.debug(customer.getLocked());
				if(customer.getLocked()==null || !customer.getLocked()){
					password = Md5Util.md5(password, customer.getCustomerAccount());
					if(password.equals(customer.getCustomerPassword())){
						json.put(SysConstants.Status.SUCCESS, true);
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "密码不正确");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID和密码不为空");
		}
		
		return json;
	}
	
	/**
	 * 用户修改温度与时间参数
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editMachineTempTimeout.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineTempTimeout(@RequestBody HaMachine machine) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machine.getMachineId())){
			HaMachine machineTemp = haMachineService.findByPrimaryKey(machine.getMachineId());
			if(machineTemp!=null){
				if(Assert.isValidString(machine.getCustomerId()) && machine.getCustomerId().equals(machineTemp.getCustomerId())){
					HaCustomer customer = haCustomerService.findByPrimaryKey(machine.getCustomerId());
					if(customer!=null){
						if(customer.getLocked()==null || !customer.getLocked()){
							if(machineTemp.getMachineOnlineStatus()!=null && machineTemp.getMachineOnlineStatus()==1){
								Date now = new Date();
								machineTemp.setModifyTime(now);
								
								machineTemp.setMachineTurnOffFireTemp(machine.getMachineTurnOffFireTemp());
								machineTemp.setMachineTurnOffPumpTemp(machine.getMachineTurnOffPumpTemp());
								machineTemp.setMachineTurnOnFireTemp(machine.getMachineTurnOnFireTemp());
								machineTemp.setMachineTurnOnPumpTemp(machine.getMachineTurnOnPumpTemp());
								machineTemp.setMachineTurnSmokeTemp(machine.getMachineTurnSmokeTemp());
								
								machineTemp.setMachineTurnOffBlowerTimeout(machine.getMachineTurnOffBlowerTimeout());
								machineTemp.setMachineTurnOffWindTimeout(machine.getMachineTurnOffWindTimeout());
								machineTemp.setMachineTurnOnPreFeedTimeout(machine.getMachineTurnOnPreFeedTimeout());
								machineTemp.setMachineTurnOnTimeout(machine.getMachineTurnOnTimeout());
								
								if(haMachineService.update(machineTemp)>0){
									json.put(HaConstact.MACHINE_ID, machineTemp.getMachineId());
									json.put(SysConstants.Status.SUCCESS, true);
									//发送修改温度与时间参数命令
									new Thread(new MachineTempTimeoutThread()).start();
								}else{
									json.put(SysConstants.Status.SUCCESS, false);
									json.put(SysConstants.Status.RESULT, "修改温度与时间参数失败");
								}
							}else{
								json.put(SysConstants.Status.SUCCESS, false);
								json.put(SysConstants.Status.RESULT, "设备离线");
							}
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "用户账号不存在");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户没有权限修改此设备的参数");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 用户修改时间段控制参数
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editMachineTimeInterval.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineTimeInterval(@RequestBody HaMachine machine) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machine.getMachineId())){
			HaMachine machineTemp = haMachineService.findByPrimaryKey(machine.getMachineId());
			if(machineTemp!=null){
				if(Assert.isValidString(machine.getCustomerId()) && machine.getCustomerId().equals(machineTemp.getCustomerId())){
					HaCustomer customer = haCustomerService.findByPrimaryKey(machine.getCustomerId());
					if(customer!=null){
						if(customer.getLocked()==null || !customer.getLocked()){
							if(machineTemp.getMachineOnlineStatus()!=null && machineTemp.getMachineOnlineStatus()==1){
								Date now = new Date();
								machineTemp.setModifyTime(now);
								
								machineTemp.setMachineWorkTimeInterval1(machine.getMachineWorkTimeInterval1());
								machineTemp.setMachineWorkTimeInterval2(machine.getMachineWorkTimeInterval2());
								machineTemp.setMachineWorkTimeInterval3(machine.getMachineWorkTimeInterval3());
								machineTemp.setMachineWorkTimeInterval4(machine.getMachineWorkTimeInterval4());
								machineTemp.setMachineWorkTimeInterval5(machine.getMachineWorkTimeInterval5());
								machineTemp.setMachineWorkTimeInterval6(machine.getMachineWorkTimeInterval6());
								machineTemp.setMachineWorkTimeInterval7(machine.getMachineWorkTimeInterval7());
								machineTemp.setMachineWorkTimeInterval8(machine.getMachineWorkTimeInterval8());
								
								if(haMachineService.update(machineTemp)>0){
									json.put(HaConstact.MACHINE_ID, machineTemp.getMachineId());
									json.put(SysConstants.Status.SUCCESS, true);
									//发送修改时间段控制参数命令
									new Thread(new MachineTimeIntervalThread()).start();
								}else{
									json.put(SysConstants.Status.SUCCESS, false);
									json.put(SysConstants.Status.RESULT, "修改时间段控制参数失败");
								}
							}else{
								json.put(SysConstants.Status.SUCCESS, false);
								json.put(SysConstants.Status.RESULT, "设备离线");
							}
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "用户账号不存在");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户没有权限修改此设备的参数");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 开机或关机
	 * @param customerId
	 * @param machineId
	 * @param turnOn
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/turnOnMachine.app",method=RequestMethod.POST)
	@ResponseBody
	public Object turnOnMachine(String customerId, String machineId, Boolean turnOn) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customerId) && Assert.isValidString(machineId) && turnOn!=null){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(customerId.equals(machine.getCustomerId())){
					HaCustomer customer = haCustomerService.findByPrimaryKey(machine.getCustomerId());
					if(customer!=null){
						if(customer.getLocked()==null || !customer.getLocked()){
							if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
								json.put(SysConstants.Status.SUCCESS, true);
								//发送开机、关机命令
								new Thread(new MachineTurnOnThread(machine, machine.getCustomerId(), turnOn)).start();
							}else{
								json.put(SysConstants.Status.SUCCESS, false);
								json.put(SysConstants.Status.RESULT, "设备离线");
							}
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "用户账号不存在");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户没有权限修改此设备的参数");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID,设备ID不为空");
		}
		
		return json;
	}
	
	/**
	 * 修改料机档位
	 * @param customerId
	 * @param machineId
	 * @param binStall
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/editMachineBinStall.app",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineBinStall(String customerId, String machineId, Integer binStall) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customerId) && Assert.isValidString(machineId) && binStall!=null){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(customerId.equals(machine.getCustomerId())){
					HaCustomer customer = haCustomerService.findByPrimaryKey(machine.getCustomerId());
					if(customer!=null){
						if(customer.getLocked()==null || !customer.getLocked()){
							if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
								Date now = new Date();
								machine.setModifyTime(now);
								machine.setMachineBinStall(binStall);
								if(haMachineService.update(machine)>0){
									json.put(SysConstants.Status.SUCCESS, true);
									//发送修改料机档位命令
									new Thread(new MachineBinStallThread()).start();
								}else{
									json.put(SysConstants.Status.SUCCESS, false);
									json.put(SysConstants.Status.RESULT, "修改料机档位失败");
								}
							}else{
								json.put(SysConstants.Status.SUCCESS, false);
								json.put(SysConstants.Status.RESULT, "设备离线");
							}
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "用户账号不存在");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户没有权限修改此设备的参数");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID,设备ID不为空");
		}
		
		return json;
	}
	
	/**
	 * 恢复出厂设置
	 * @param customerId
	 * @param machineId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/recoverMachine.app",method=RequestMethod.POST)
	@ResponseBody
	public Object recoverMachine(String customerId, String machineId) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customerId) && Assert.isValidString(machineId)){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(customerId.equals(machine.getCustomerId())){
					HaCustomer customer = haCustomerService.findByPrimaryKey(machine.getCustomerId());
					if(customer!=null){
						if(customer.getLocked()==null || !customer.getLocked()){
							if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
								json.put(SysConstants.Status.SUCCESS, true);
								//发送恢复出厂设置命令，恢复出厂设置后，需要返回一份最新的设备信息
								new Thread(new MachineRecoverThread()).start();
							}else{
								json.put(SysConstants.Status.SUCCESS, false);
								json.put(SysConstants.Status.RESULT, "设备离线");
							}
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "用户账号不存在");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户没有权限修改此设备的参数");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID,设备ID不为空");
		}
		
		return json;
	}
	
	//管理员修改使用期限 这个这里不需要
	
	/**
	 * 获取用户权限下的设备
	 * @param machineQueryBean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/findMachineByCustomer.app",method=RequestMethod.POST)
	@ResponseBody
	public Object findMachineByCustomer(@RequestBody HaMachineQueryBean machineQueryBean) throws Exception{
		log.debug(machineQueryBean.getLimit()+";"+machineQueryBean.getOffset()
				+";"+machineQueryBean.getOrderBy()+";"+machineQueryBean.isDesc()
				+";"+machineQueryBean.isOr());
		if(Assert.isValidString(machineQueryBean.getCustomerId())){
			HaCustomer customer = haCustomerService.findByPrimaryKey(machineQueryBean.getCustomerId());
			if(customer==null){
				log.debug("用户不存在");
				return machineQueryBean;
			}else if(customer.getLocked()!=null && customer.getLocked()){
				log.debug("用户被锁定");
				return machineQueryBean;
			}
		}else{
			log.debug("用户ID不为空");
			return machineQueryBean;
		}
		QueryBean<HaMachine> queryBean = haMachineService.findMachineByCustomer(machineQueryBean);
//		new Thread(new MachineFlushTask(queryBean.getResult())).start();
		
		return queryBean;
	}
	
	/**
	 * 查找用户指定的设备信息
	 * @param customerId
	 * @param machineId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/findMachineById.app",method=RequestMethod.POST)
	@ResponseBody
	public Object findMachineById(String customerId, String machineId) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customerId) && Assert.isValidString(machineId)){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(customerId.equals(machine.getCustomerId()) || customerId.equals(machine.getCustomerId1())
						|| customerId.equals(machine.getCustomerId2()) || customerId.equals(machine.getCustomerId3())){
					HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
					if(customer!=null){
						if(customer.getLocked()==null || !customer.getLocked()){
							json.put(SysConstants.Status.SUCCESS, true);
							json.put(SysConstants.Status.RESULT, machine);
							if(Assert.isValidString(machine.getCustomerId())){
								HaCustomer c = haCustomerService.findByPrimaryKey(machine.getCustomerId());
								if(c!=null){
									json.put(c.getCustomerId(), c);
								}
							}
							if(Assert.isValidString(machine.getCustomerId1())){
								HaCustomer c = haCustomerService.findByPrimaryKey(machine.getCustomerId1());
								if(c!=null){
									json.put(c.getCustomerId(), c);
								}
							}
							if(Assert.isValidString(machine.getCustomerId2())){
								HaCustomer c = haCustomerService.findByPrimaryKey(machine.getCustomerId2());
								if(c!=null){
									json.put(c.getCustomerId(), c);
								}
							}
							if(Assert.isValidString(machine.getCustomerId3())){
								HaCustomer c = haCustomerService.findByPrimaryKey(machine.getCustomerId3());
								if(c!=null){
									json.put(c.getCustomerId(), c);
								}
							}
							
							if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
								//启动线程命令设备刷新设备信息
								new Thread(new MachineStatusFlushThread(machine)).start();
							}
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "用户账号不存在");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户对设备没有权限");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID、设备ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 用户删除设备信息
	 * @param customerId
	 * @param machineId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/removeMachine.app",method=RequestMethod.POST)
	@ResponseBody
	public Object removeMachine(String customerId, String machineId) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customerId) && Assert.isValidString(machineId)){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				Date now = new Date();
				machine.setModifyTime(now);
				boolean hasRight = false;
				if(customerId.equals(machine.getCustomerId())){
					machine.setCustomerId(null);
					hasRight = true;
				}
				if(customerId.equals(machine.getCustomerId1())){
					machine.setCustomerId1(null);
					hasRight = true;
				}
				if(customerId.equals(machine.getCustomerId2())){
					machine.setCustomerId2(null);
					hasRight = true;
				}
				if(customerId.equals(machine.getCustomerId3())){
					machine.setCustomerId3(null);
					hasRight = true;
				}
				if(hasRight){
					HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
					if(customer!=null){
						if(customer.getLocked()==null || !customer.getLocked()){
							if(haMachineService.update(machine)>0){
								json.put(HaConstact.MACHINE_ID, machine.getMachineId());
								json.put(SysConstants.Status.SUCCESS, true);
							}else{
								json.put(SysConstants.Status.SUCCESS, false);
								json.put(SysConstants.Status.RESULT, "移除设备失败");
							}
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "用户账号被锁定，无法使用");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "用户账号不存在");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户对设备没有权限");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID、设备ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 提交反馈
	 * @param customerId
	 * @param feedbackContent
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/feedback.app",method=RequestMethod.POST)
	@ResponseBody
	public Object feedback(String customerId, String feedbackContent) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customerId) && Assert.isValidString(feedbackContent)){
			HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
			if(customer!=null){
				HaFeedback feedback = new HaFeedback();
				feedback.setFeedbackContent(feedbackContent);
				feedback.setCustomerId(customerId);
				feedback.setCustomerAccount(customer.getCustomerAccount());
				feedback.setCustomerName(customer.getCustomerName());
				feedback.setDeviceModel(customer.getDeviceModel());
				feedback.setDeviceSystem(customer.getDeviceSystem());
				feedback.setDeviceVendor(customer.getDeviceVendor());
				feedback.setCreateTime(new Date());
				if(haFeedbackService.save(feedback)>0){
					json.put(SysConstants.Status.SUCCESS, true);
					json.put(SysConstants.Status.RESULT, feedback.getFeedbackId());
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "提交保存失败");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID、反馈意见不为空");
		}
		
		return json;
	}
	
	/**
	 * 逆向地理解析
	 * @param location
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/reGeocoder.app",method=RequestMethod.POST)
	@ResponseBody
	public Object removeMachine(String location) throws Exception{
		return JSONObject.parse(BaiduGeocoderUtil.reGeocoder(location));
	}
	
	/**
	 * 返回重新登录
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/relogin.app",method={RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.PUT})
	@ResponseBody
	public Object relogin() throws Exception{
		JSONObject json = new JSONObject();
		json.put(SysConstants.Status.SUCCESS, false);
		json.put(SysConstants.Status.RESULT, "relogin");
		return json;
	}
}
